﻿using Newtonsoft.Json;
using QD.Tools;
using QD.UpDownLoad;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using QD.SQLHelper;

namespace QD.SyncServers
{
    public partial class SyncStep5 : BaseFrm
    {        
        public SyncStep5()
        {
            InitializeComponent();
            this.gridMasterSyncLog.AutoGenerateColumns = false;
            this.gridConfigSyncLog.AutoGenerateColumns = false;
        }

        private void SyncStep5_Load(object sender, EventArgs e)
        {
            this.label1.Text = "同步结果";
            if (ConfigInstanceHelper.ConfigInstance.MasterSyncLogDS != null && ConfigInstanceHelper.ConfigInstance.MasterSyncLogDS.Tables.Count > 0)
            {
                this.gridMasterSyncLog.DataSource = ConfigInstanceHelper.ConfigInstance.MasterSyncLogDS.Tables[0];
            }   
            if (ConfigInstanceHelper.ConfigInstance.ConfigSyncLogDS != null && ConfigInstanceHelper.ConfigInstance.ConfigSyncLogDS.Tables.Count > 0)
            {
                this.gridConfigSyncLog.DataSource = ConfigInstanceHelper.ConfigInstance.ConfigSyncLogDS.Tables[0];
            }
            this.txtErrorMessage.Text = ConfigInstanceHelper.ConfigInstance.ErrorMessage;

            //添加搜索栏位(主数据库同步日志)
            DataGridViewColumnCollection columns = this.gridMasterSyncLog.Columns;
            for(int i = 0;i < columns.Count;i++)
            {
                if (!string.IsNullOrEmpty(columns[i].DataPropertyName))
                {
                    ComboBoxItem item = new ComboBoxItem(columns[i].DataPropertyName, columns[i].HeaderText);
                    this.cbxMasterSearchColumnName.Items.Add(item);
                }
            }

            //添加搜索栏位(配置数据库同步日志)
            columns = this.gridConfigSyncLog.Columns;
            for (int i = 0; i < columns.Count; i++)
            {
                if (!string.IsNullOrEmpty(columns[i].DataPropertyName))
                {
                    ComboBoxItem item = new ComboBoxItem(columns[i].DataPropertyName, columns[i].HeaderText);
                    this.cbxConfigSearchColumnName.Items.Add(item);
                }
            }

            if (!string.IsNullOrEmpty(ConfigInstanceHelper.ConfigInstance.ErrorMessage))
            {
                this.tpErrorMessage.Focus();
            }
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form frm = Application.OpenForms["SyncStep4"];

            if (frm == null)
            {
                frm = new SyncStep4();
                frm.ShowDialog();
            }
            else
            {
                frm.Show();
            }
        }

        //显示行号
        private void gridMasterSyncLog_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, gridMasterSyncLog.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), gridMasterSyncLog.RowHeadersDefaultCellStyle.Font, rectangle, gridMasterSyncLog.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        //显示行号
        private void gridConfigSyncLog_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, gridConfigSyncLog.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), gridConfigSyncLog.RowHeadersDefaultCellStyle.Font, rectangle, gridConfigSyncLog.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void btnMasterSearch_Click(object sender, EventArgs e)
        {
            searchDataForMasterSynclog(-1, true);
            //object dataSourceObj = this.gridMasterSyncLog.DataSource;
            //if (dataSourceObj != null)
            //{
            //    DataTable dtSource = dataSourceObj as DataTable;
            //    if (!string.IsNullOrEmpty(serachColumnName) && !string.IsNullOrEmpty(searchColumnValue))
            //    {                    
            //        string columnDataTypeName = dtSource.Columns[serachColumnName].DataType.Name.ToLower();
            //        if (columnDataTypeName.StartsWith("int") || columnDataTypeName.StartsWith("uint") || 
            //            columnDataTypeName.StartsWith("long") || columnDataTypeName.StartsWith("ulong") || 
            //            columnDataTypeName.StartsWith("decimal") || columnDataTypeName.StartsWith("double") || 
            //            columnDataTypeName.StartsWith("float") || columnDataTypeName.StartsWith("bool"))
            //        {
            //            rowFilter = serachColumnName + " = " + searchColumnValue;
            //        }
            //        else
            //        {
            //            rowFilter = serachColumnName + " like '%" + searchColumnValue + "%'";
            //        }
            //    }
            //    dtSource.DefaultView.RowFilter = rowFilter;
            //}

        }

        private void searchDataForMasterSynclog(int beginRowIndex, bool searchDownward)
        {
            this.gridMasterSyncLog.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.gridMasterSyncLog.MultiSelect = true;
            this.gridMasterSyncLog.ClearSelection();
            
            string serachColumnName = "";
            if (this.cbxMasterSearchColumnName.SelectedItem != null)
            {
                serachColumnName = ((ComboBoxItem)this.cbxMasterSearchColumnName.SelectedItem).Key;
            }
            string searchColumnValue = this.txtMasterSearchColumnValue.Text;
            int rowsCount = this.gridMasterSyncLog.Rows.Count;
            int firstSelectedRowIndex = -1;
            List<int> selectedRowIndexList = new List<int>();
            int rowIndex = -1;
            string operatorType = "like";

            if (!string.IsNullOrEmpty(serachColumnName) && !string.IsNullOrEmpty(searchColumnValue))
            {
                if (searchColumnValue.StartsWith("="))
                {
                    operatorType = "=";
                    searchColumnValue = searchColumnValue.Substring(1);
                }
                else if (searchColumnValue.StartsWith("%") && searchColumnValue.EndsWith("%"))
                {
                    operatorType = "like";
                    searchColumnValue = searchColumnValue.Substring(1, searchColumnValue.Length - 2);
                }
                else if (searchColumnValue.StartsWith("%") && !searchColumnValue.EndsWith("%"))
                {
                    operatorType = "rightlike";
                    searchColumnValue = searchColumnValue.Substring(1);
                }
                else if (!searchColumnValue.StartsWith("%") && searchColumnValue.EndsWith("%"))
                {
                    operatorType = "leftlike";
                    searchColumnValue = searchColumnValue.Substring(0, searchColumnValue.Length - 1);
                }
                else
                {
                    operatorType = "like";
                }

                if (!string.IsNullOrEmpty(searchColumnValue))
                {
                    for (int i = 0; i < rowsCount; i++)
                    {
                        string columnValue = this.gridMasterSyncLog.Rows[i].GetCellValueToString(serachColumnName);

                        bool matchTag = false;

                        if (!string.IsNullOrEmpty(columnValue))
                        {
                            if (columnValue.ToLower() == "true")
                            {
                                columnValue = "1";
                            }
                            else if (columnValue.ToLower() == "false")
                            {
                                columnValue = "0";
                            }
                            if ((operatorType == "=" && columnValue.ToLower() == searchColumnValue.ToLower())
                                || (operatorType == "like" && columnValue.ToLower().Contains(searchColumnValue.ToLower()))
                                || (operatorType == "rightlike" && columnValue.ToLower().EndsWith(searchColumnValue.ToLower()))
                                || (operatorType == "leftlike" && columnValue.ToLower().StartsWith(searchColumnValue.ToLower()))
                                )
                            {
                                this.gridMasterSyncLog.Rows[i].Selected = true;
                                selectedRowIndexList.Add(i);
                                if (searchDownward && i > beginRowIndex && firstSelectedRowIndex == -1)
                                {
                                    firstSelectedRowIndex = i;
                                }
                                else if (!searchDownward && i < beginRowIndex && i > firstSelectedRowIndex)
                                {
                                    firstSelectedRowIndex = i;
                                }
                            }
                        }
                    }
                    if (firstSelectedRowIndex != -1)
                    {
                        this.gridMasterSyncLog.FirstDisplayedScrollingRowIndex = firstSelectedRowIndex;
                        this.gridMasterSyncLog.CurrentCell = this.gridMasterSyncLog.Rows[firstSelectedRowIndex].Cells[0];//设定当前行
                        //重新选中行（this.gridMasterSyncLog.CurrentCell会取消选择）
                        for (int i = 0; i < selectedRowIndexList.Count; i++)
                        {
                            rowIndex = selectedRowIndexList[i];
                            this.gridMasterSyncLog.Rows[rowIndex].Selected = true;
                        }
                    }
                }
            }
        }

        private void btnMasterSearchNext_Click(object sender, EventArgs e)
        {
            int rowIndex = -1;
            DataGridViewCell gridViewCell = this.gridMasterSyncLog.CurrentCell;
            if (gridViewCell != null)
            {
                rowIndex = gridViewCell.RowIndex;
            }
            searchDataForMasterSynclog(rowIndex, true);
        }

        private void btnMasterSearchPrev_Click(object sender, EventArgs e)
        {
            int rowIndex = -1;
            DataGridViewCell gridViewCell = this.gridMasterSyncLog.CurrentCell;
            if (gridViewCell != null)
            {
                rowIndex = gridViewCell.RowIndex;
            }
            searchDataForMasterSynclog(rowIndex, false);
        }
        private void searchDataForConfigSynclog(int beginRowIndex, bool searchDownward)
        {
            this.gridConfigSyncLog.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.gridConfigSyncLog.MultiSelect = true;
            this.gridConfigSyncLog.ClearSelection();

            string serachColumnName = "";
            if (this.cbxConfigSearchColumnName.SelectedItem != null)
            {
                serachColumnName = ((ComboBoxItem)this.cbxConfigSearchColumnName.SelectedItem).Key;
            }            
            string searchColumnValue = this.txtConfigSearchColumnValue.Text;
            int rowsCount = this.gridConfigSyncLog.Rows.Count;
            int firstSelectedRowIndex = -1;
            List<int> selectedRowIndexList = new List<int>();
            int rowIndex = -1;
            string operatorType = "like";

            if (!string.IsNullOrEmpty(serachColumnName) && !string.IsNullOrEmpty(searchColumnValue))
            {
                if (searchColumnValue.StartsWith("="))
                {
                    operatorType = "=";
                    searchColumnValue = searchColumnValue.Substring(1);
                }
                else if (searchColumnValue.StartsWith("%") && searchColumnValue.EndsWith("%"))
                {
                    operatorType = "like";
                    searchColumnValue = searchColumnValue.Substring(1, searchColumnValue.Length - 2);
                }
                else if (searchColumnValue.StartsWith("%") && !searchColumnValue.EndsWith("%"))
                {
                    operatorType = "rightlike";
                    searchColumnValue = searchColumnValue.Substring(1);
                }
                else if (!searchColumnValue.StartsWith("%") && searchColumnValue.EndsWith("%"))
                {
                    operatorType = "leftlike";
                    searchColumnValue = searchColumnValue.Substring(0, searchColumnValue.Length - 1);
                }
                else
                {
                    operatorType = "like";
                }

                if (!string.IsNullOrEmpty(searchColumnValue))
                {
                    for (int i = 0; i < rowsCount; i++)
                    {
                        string columnValue = this.gridMasterSyncLog.Rows[i].GetCellValueToString(serachColumnName);

                        bool matchTag = false;

                        if (!string.IsNullOrEmpty(columnValue))
                        {
                            if (columnValue.ToLower() == "true")
                            {
                                columnValue = "1";
                            }
                            else if (columnValue.ToLower() == "false")
                            {
                                columnValue = "0";
                            }

                            if ((operatorType == "=" && columnValue.ToLower() == searchColumnValue.ToLower())
                                || (operatorType == "like" && columnValue.ToLower().Contains(searchColumnValue.ToLower()))
                                || (operatorType == "rightlike" && columnValue.ToLower().EndsWith(searchColumnValue.ToLower()))
                                || (operatorType == "leftlike" && columnValue.ToLower().StartsWith(searchColumnValue.ToLower()))
                                )
                            {
                                this.gridMasterSyncLog.Rows[i].Selected = true;
                                selectedRowIndexList.Add(i);
                                if (searchDownward && i > beginRowIndex && firstSelectedRowIndex == -1)
                                {
                                    firstSelectedRowIndex = i;
                                }
                                else if (!searchDownward && i < beginRowIndex && i > firstSelectedRowIndex)
                                {
                                    firstSelectedRowIndex = i;
                                }
                            }
                        }
                    }
                    if (firstSelectedRowIndex != -1)
                    {
                        this.gridConfigSyncLog.FirstDisplayedScrollingRowIndex = firstSelectedRowIndex;
                        this.gridConfigSyncLog.CurrentCell = this.gridConfigSyncLog.Rows[firstSelectedRowIndex].Cells[0];//设定当前行
                        //重新选中行（this.gridMasterSyncLog.CurrentCell会取消选择）
                        for (int i = 0; i < selectedRowIndexList.Count; i++)
                        {
                            rowIndex = selectedRowIndexList[i];
                            this.gridConfigSyncLog.Rows[rowIndex].Selected = true;
                        }
                    }
                }
            }
        }

        private void btnConfigSearchPrev_Click(object sender, EventArgs e)
        {
            int rowIndex = -1;
            DataGridViewCell gridViewCell = this.gridConfigSyncLog.CurrentCell;
            if (gridViewCell != null)
            {
                rowIndex = gridViewCell.RowIndex;
            }
            searchDataForConfigSynclog(rowIndex, false);
        }

        private void btnConfigSearchNext_Click(object sender, EventArgs e)
        {
            int rowIndex = -1;
            DataGridViewCell gridViewCell = this.gridConfigSyncLog.CurrentCell;
            if (gridViewCell != null)
            {
                rowIndex = gridViewCell.RowIndex;
            }
            searchDataForConfigSynclog(rowIndex, true);
        }

        private void btnConfigSearch_Click(object sender, EventArgs e)
        {
            searchDataForConfigSynclog(-1, true);
        }
    }
}
